﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NHibernate;
using NHibernate.Cfg;
using NHibernate.Tool.hbm2ddl;

namespace NHibernateBusiness.Common
{
    public class ISessionDataFactory
    {
        private static ISessionFactory _sessionFactory = null;
        private static object _locker = new object();
        private static ISessionStorage _sessionStorage = null;
        private static Configuration _configuration = null;

        /// <summary>
        /// 获取配置信息
        /// </summary>
        private static Configuration Configuration
        {
            get
            {
                lock (_locker)
                {
                    if (_configuration == null)
                    {
                        _configuration = new Configuration().Configure();
                    }
                    return _configuration;
                }
            }
        }

        internal static ISessionFactory GetSessionFactory
        {
            get
            {
                if (_sessionFactory == null)
                {
                    lock (_locker)
                    {
                        _sessionFactory = Configuration.BuildSessionFactory();
                    }
                }
                return _sessionFactory;
            }
        }

        /// <summary>
        /// 获取Session
        /// </summary>
        /// <returns></returns>
        public static ISession GetSession()
        {
            if (_sessionStorage == null)
            {
                _sessionStorage = new HttpSessionSource();
            }
            ISession session = _sessionStorage.Get();
            if (session == null)
            {
                session = GetSessionFactory.OpenSession();
                _sessionStorage.Set(session);
            }
            return session;
        }

        /// <summary>
        /// 根据Mapping、实体类生成数据库（未测试）
        /// </summary>
        public static  void CreateDataTable()
        {
            SchemaMetadataUpdater.QuoteTableAndColumns(Configuration);
            new SchemaExport(Configuration).Create(false, true);
        }
    }
}
